const axios = require('axios');

const refreshTokens = process.env.ALIYUNPAN_REFRESH_TOKEN?.split('&') || [];

if (refreshTokens.length === 0) {
  console.log('请先设置ALIYUNPAN_REFRESH_TOKEN环境变量');
  process.exit(1);
}

// 获取access_token（稳定接口）
async function getAccessToken(refreshToken) {
  try {
    const res = await axios({
      url: 'https://auth.aliyundrive.com/v2/account/token',
      method: 'post',
      data: {
        grant_type: 'refresh_token',
        refresh_token: refreshToken,
        client_id: '25dzX3vbYqktVxyX'
      },
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      }
    });
    if (!res.data.access_token) throw new Error('未获取到access_token');
    return res.data.access_token;
  } catch (err) {
    throw new Error(`token获取失败：${err.response?.data?.message || err.message}`);
  }
}

// 执行签到（最新可用接口）
async function signIn(accessToken) {
  try {
    const res = await axios({
      url: 'https://member.aliyundrive.com/v1/activity/sign_in',
      method: 'post',
      data: {},
      headers: {
        Authorization: `Bearer ${accessToken}`,
        'Content-Type': 'application/json;charset=UTF-8',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 AliApp(DingTalk/7.0.0) com.alibaba.android.rimet/13834869 Channel/201200 language/zh-CN'
      }
    });
    return res.data;
  } catch (err) {
    if (err.response?.status === 400) {
      const errMsg = err.response.data?.message || '今日已签到';
      return { code: 'AlreadySignIn', message: errMsg };
    }
    throw new Error(`签到接口错误：${err.response?.status || err.message}`);
  }
}

// 获取签到信息（验证签到结果）
async function getSignData(accessToken) {
  try {
    const res = await axios({
      url: 'https://member.aliyundrive.com/v1/activity/sign_in_list',
      method: 'post',
      data: { page: 1, pageSize: 31 },
      headers: {
        Authorization: `Bearer ${accessToken}`,
        'Content-Type': 'application/json;charset=UTF-8'
      }
    });
    return res.data;
  } catch (err) {
    throw new Error(`获取签到信息失败：${err.message}`);
  }
}

// 格式化空间大小（字节转MB/GB）
function formatSpace(spaceBytes) {
  if (!spaceBytes) return '0MB';
  const mb = spaceBytes / (1024 * 1024);
  return mb >= 1024 
    ? `${(mb / 1024).toFixed(2)}GB` 
    : `${Math.round(mb)}MB`;
}

// 主函数
async function main() {
  const startTime = new Date();
  let message = `📅 阿里云盘自动签到结果（${startTime.toLocaleString()}）\n`;
  message += `========================================\n\n`;
  
  let successCount = 0;
  let failCount = 0;
  
  for (let i = 0; i < refreshTokens.length; i++) {
    const token = refreshTokens[i].trim();
    if (!token) continue;
    
    message += `【账号 ${i + 1}】\n`;
    try {
      // 1. 获取access_token
      const accessToken = await getAccessToken(token);
      
      // 2. 执行签到
      const signRes = await signIn(accessToken);
      
      // 3. 获取签到详情
      const signData = await getSignData(accessToken);
      
      // 4. 解析结果
      const continuousDays = signData.continuousSignInCount || 0;
      const totalDays = signData.totalSignInCount || 0;
      // 获取今日签到奖励（最新一条记录）
      const todayReward = signData.signInLogs?.[0]?.reward?.space;
      
      if (signRes.code === 'AlreadySignIn') {
        message += `✅ 状态：今日已签到\n`;
      } else {
        message += `✅ 状态：签到成功\n`;
        successCount++;
      }

    } catch (err) {
      message += `❌ 状态：签到失败\n`;
      message += `❓ 原因：${err.message}\n`;
      failCount++;
    }
    message += `----------------------------------------\n`;
  }
  
  // 总结信息
  message += `\n📝 本次签到总结\n`;
  message += `总账号数：${refreshTokens.length}个\n`;
  message += `成功：${successCount}个 | 失败：${failCount}个\n`;
  message += `耗时：${(new Date() - startTime) / 1000}秒\n`;
  
  console.log(message);
}

main().catch(err => console.error('❌ 总错误：', err.message));